import React, { PureComponent, Fragment } from 'react';
import { Upload as Up, Icon, Layout, Button, Row, Col, Input, message, Modal, Alert } from 'antd';
import BlankHeader from '../../components/BlankHeader';
import styles from './index.less';

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

export default class Upload extends PureComponent {
  state = {
    imageUrl: '',
    brife: '',
  };

  handleGoBack = () => {
    const { history } = this.props;
    history.goBack();
  };

  handleChange = info => {
    if (info.fileList[info.fileList.length - 1].size > 1048576) {
      Modal.error({
        title: '错误',
        content: '照片太大，最大1MB！',
      });
    } else if (info.fileList[info.fileList.length - 1].originFileObj) {
      getBase64(info.fileList[info.fileList.length - 1].originFileObj, imageUrl =>
        this.setState({
          imageUrl,
        })
      );
    }
  };

  handleText = e => {
    this.setState({ brife: e.target.value });
  };

  handleSubmit = () => {
    const { imageUrl, brife } = this.state;

    if (imageUrl === '') {
      message.warning('请添加照片！');
    } else if (/\s/.test(brife) || brife === '') {
      message.warning('照片描述不能为空！');
    } else {
      localStorage.setItem('tempImg', imageUrl);
      localStorage.setItem('brife', brife);
      window.location.replace('/process');
    }
  };

  render() {
    const { imageUrl, brife } = this.state;

    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">添加</div>
      </div>
    );

    return (
      <Fragment>
        <BlankHeader onClick={this.handleGoBack}>发布</BlankHeader>
        <Layout className={styles.wrapper}>
          <Row>
            <Col offset={1} span={22} className={styles.uploadWrapper}>
              <Up
                accept="image/*"
                listType="picture-card"
                showUploadList={false}
                onChange={this.handleChange}
                beforeUpload={() => false}
              >
                {imageUrl ? <img src={imageUrl} alt="avatar" /> : uploadButton}
              </Up>
            </Col>
          </Row>
          <Row>
            <Alert message="由于是学生服务器，故照片大小限制1MB，请谅解！谢谢！" type="warning" />
          </Row>
          <Row style={{ marginTop: '20px' }}>
            <Col offset={1}>照片描述：</Col>
          </Row>
          <Row>
            <Col offset={1} span={22}>
              <Input value={brife} onChange={this.handleText} placeholder="想说点什么..." />
            </Col>
          </Row>
          <Row style={{ marginTop: '50px' }}>
            <Col span={24} style={{ textAlign: 'center' }}>
              <Button size="large" type="primary" onClick={this.handleSubmit}>
                确定
              </Button>
            </Col>
          </Row>
        </Layout>
      </Fragment>
    );
  }
}
